import {RubbishJSObfuscator} from "./RubbishJSObfuscator.js";

function randomWord(range) {
    var str = "",
        arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    var arr2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_', '$'];

    // arr = ['$'];
    // 随机产生
    for (var i = 0; i < range; i++) {
        if (i == 0) {
            let pos = Math.round(Math.random() * (arr.length - 1));
            str += arr[pos];
        } else {
            let pos = Math.round(Math.random() * (arr2.length - 1));
            str += arr2[pos];
        }
    }
    return str;
}

function xor_enc(str, key) {
    var crytxt = [];
    var k, keylen = key.length;
    for(var i=0; i<str.length; i++) {
        k = i % keylen;
        crytxt.push(str.charCodeAt(i) ^ key.charCodeAt(k));
    }
    return crytxt;
}

export function generateRuntimeCheckCode(runtimeAppId, targetEnvVersionMap) {
    let xorKey = randomWord(8);
    const xorResult = xor_enc(runtimeAppId, xorKey);

    // language=js
    const code = `
        // @ts-ignore
    if (cc.sys.platform === cc.sys.Platform.WECHAT_GAME && Math.random() < 0.1) {
        // @ts-ignore
        const miniProgram = GameGlobal["wx"]["getAccountInfoSync"]()["miniProgram"];
        ${xor_enc}
        if (xor_enc(miniProgram["appId"], "${xorKey}").toString() != "${xorResult}" && ${JSON.stringify(targetEnvVersionMap)}[miniProgram["envVersion"]]) {
            return
        }
    }`


    let jsObfuscator = new RubbishJSObfuscator(code);

    jsObfuscator.dot2String();
// jsObfuscator.generateCode();
    jsObfuscator.processString();
    jsObfuscator.uglifyJSMinify();

    return {
        code: code,
        minify: `// @ts-ignore\n${jsObfuscator.code}`
    }
}
